import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
use_library('django', '0.96')
from os import environ
from models import *
import datetime
import random
import re

logout="""<p><a href="http://localhost:8080/_ah/login?continue=http%3A//localhost%3A8080/&action=Logout">Logout</a></p>"""

go="""	<form action="/choice" method="get">
		<input type="submit" value="Continue">
	</form>
"""

class notificationPage(webapp.RequestHandler,db.Model):
	def get(self):
		global user,usr 
		user = users.get_current_user()
		if user:
			self.response.out.write('Hello, '+user.nickname())
			path = os.path.join(os.path.dirname(__file__),'test.html')
			self.response.out.write(template.render(path,{}))
			self.response.out.write(logout)
		else:
		        self.redirect(users.create_login_url(self.request.uri))
		
	def validate_emailid(self,emailid):					#validating email ids
		if (re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", emailid)):
			return 1
		else:
			return 0
		
	def post(self):
		user = users.get_current_user()
		u=user.email()
		email=self.request.get("emailadr")
		emailid=email.split(',')
		n=1
		f=0
		f2=0
		rest=""
		not_id=""
		frm_usrid=""
		userDetails=db.GqlQuery("SELECT * FROM userDetails")
		for usr in userDetails:				
			if (usr.email==u):
				frm_usrid=usr.userid
				f2=0
				break		
			else:
				f2=1
		
		if (f2!=0):
			self.response.out.write("No user details available for current user! \n")
		else:
			for i in emailid:
				a=i
				if(a!=""):
					check=self.validate_emailid(i)
					if(check==1):
						userDetails=db.GqlQuery("SELECT * FROM userDetails")
						for usr in userDetails:
							if (usr.email==a):
								rest=usr.userid+', '+rest
								not_id="NOTIFICATION"+str(random.randint(0,400))
								n=notificationDetails(notificationid=not_id,frm_userid=frm_usrid,to_userid=usr.userid)
								n.put()
								path2 = os.path.join(os.path.dirname(__file__),'msg.html')
								self.response.out.write(template.render(path2,{'msg':' Notifications sent to: '+i}))
								f=emailid.index(a)
							else:	
								not_found=emailid.index(a)
						if (f<emailid.index(a)):
							path2 = os.path.join(os.path.dirname(__file__),'msg.html')
							self.response.out.write(template.render(path2,{'msg':'No records found for :'+a}))
					else:
						path2 = os.path.join(os.path.dirname(__file__),'msg.html')
						self.response.out.write(template.render(path2,{'msg':i+' is not a valid email id!'}))
			if(rest!=""):
				tid="CS"+str(random.randint(0,140))
				team=teamDetails(teamid=tid,teammember=rest+frm_usrid)
				team.put()
			self.response.out.write(go)

application = webapp.WSGIApplication([('/', notificationPage)],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
